﻿using Domain.IRepositorys;
using Domain.Services;
using Domain.Types;
using DTO;
using Infrastructure.Error;
using Infrastructure.UniOfWorkBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Application.App
{
    public class WalletApplication
    {
        public IUserRepository userRepository { get; set; }
        public IWalletRepository walletRepository { get; set; }
        public ISmsCodeRepository smsCodeRepository { get; set; }
        public IInComeWalletLogRepository inComeWalletLogRepository { get; set; }
        public IChargeWalletLogRepository chargeWalletLogRepository { get; set; }
        public ITaskTakeRepository taseTakeRepository { get; set; }
        public PayService payService { get; set; }
        public WalletService walletService { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public UserBlanceInfoOutput GetUserBlanceInfo(int uid)
        {
            UserBlanceInfoOutput userBlanceInfoOutput = new UserBlanceInfoOutput();

            var wallet = walletRepository.Entities.FirstOrDefault(i => i.UserID == uid);

            userBlanceInfoOutput.InComeBlance = wallet.InComeBlance;
            userBlanceInfoOutput.ChargeBlance = wallet.ChargeBlance;
            userBlanceInfoOutput.MarginBlance = wallet.MarginBlance;
            userBlanceInfoOutput.AliPayAccount = wallet.AliPayAccount;
            userBlanceInfoOutput.AliPayAccountName = wallet.AliPayAccountName;
            userBlanceInfoOutput.WxPayAccount = wallet.WxPayAccount;
            userBlanceInfoOutput.WxPayAccountName = wallet.WxPayAccountName;

            return userBlanceInfoOutput;
        }

        public UserBlanceInfoSumOutput GetUserBlanceInfoSum(int uid)
        {
            UserBlanceInfoSumOutput userBlanceInfoSum = new UserBlanceInfoSumOutput();

            var sumMoney = inComeWalletLogRepository.Entities.Where(i => i.UserID == uid && i.CT >= DateTime.Today && i.ChangeMoney > 0).Sum(i => i.ChangeMoney);
            userBlanceInfoSum.DayInCome = sumMoney;

            var sumAuditMoney = taseTakeRepository.Entities.Where(i => i.UserID == uid && i.Status == TaskTakeAuditStatus.待审核).Sum(i => i.PreFee);
            userBlanceInfoSum.BeAuditInCome = sumAuditMoney;


            return userBlanceInfoSum;
        }


        public bool ChargeMarginBlance(int uid, int money)
        {
            return payService.ChargeMarginBlance(uid, money);
        }
        /// <summary>
        /// 提现发布余额
        /// </summary>
        /// <param name="v"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public WithDrawAggregate WithDrawMoneyByCharge(int uid, PayChannelEnum payChannel, int money)
        {
            return walletService.WithDrawMoneyByCharge(uid, payChannel, money);
        }

        public IList<WalletDetailsOutput> GetUserBlanceDetails(int uid, int type, int page, int size)
        {
            if (page > 0) page = page - 1;
            if (type == 0)
            {
                var list = inComeWalletLogRepository.Entities.Where(i => i.UserID == uid).OrderByDescending(i => i.CT);

                var pageList = list.Skip(page * size).Take(size).ToList();

                return WalletDetailsOutput.Parse(pageList);
            }
            else
            {
                var list = chargeWalletLogRepository.Entities.Where(i => i.UserID == uid).OrderByDescending(i => i.CT);

                var pageList = list.Skip(page * size).Take(size).ToList();

                return WalletDetailsOutput.Parse(pageList);
            }
        }

        public object GetUserWithDrawDetails(int uid)
        {
            var u = userRepository.GetByKey(uid);

            var key = "提现配置.提现手续费";
            var feeper = u.GetTraderLevelConfig<int>(key) > u.GetLevelConfig<int>(key) ? u.GetTraderLevelConfig<int>(key) : u.GetLevelConfig<int>(key);

            key = "提现配置.每笔最大金额";
            var maxfee = u.GetTraderLevelConfig<int>(key) > u.GetLevelConfig<int>(key) ? u.GetTraderLevelConfig<int>(key) : u.GetLevelConfig<int>(key);

            key = "提现配置.最低提现金额";
            var minfee = u.GetTraderLevelConfig<int>(key) > u.GetLevelConfig<int>(key) ? u.GetTraderLevelConfig<int>(key) : u.GetLevelConfig<int>(key);


            key = "提现配置.每天提现次数";
            var dayTX = u.GetTraderLevelConfig<int>(key) > u.GetLevelConfig<int>(key) ? u.GetTraderLevelConfig<int>(key) : u.GetLevelConfig<int>(key);

            string text = $"1、提现{minfee / 100}元起，单笔{feeper}%手续费\n2、每天可提现{dayTX}次，每笔最多{maxfee / 100}元，3个工作日内到账，节假日延后到工作日发放";

            return new { text,textarr=text.Split('\n'), txper = feeper };
        }

        /// <summary>
        /// 提现冲值余额
        /// </summary>
        /// <param name="v"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public WithDrawAggregate WithDrawMoneyByInCome(int uid, PayChannelEnum payChannel, int money)
        {
            return walletService.WithDrawMoneyByInCome(uid, payChannel, money);
        }

        public bool SetAliPayInfo(int uid,string phoneCode, string account, string realName)
        {
            var u = userRepository.GetByKey(uid);
            var code = smsCodeRepository.Entities.FirstOrDefault(i => i.Phone == u.Phone && i.SmsCodeType == SmsCodeType.设置支付宝微信 && i.SmsCode == phoneCode);

            if (code == null)
            {
                throw new BizException("手机验证码不正确");
            }
            code.Valid();
            code.IsUse = true;

            var w = walletRepository.Entities.FirstOrDefault(i => i.UserID == uid);

            if (string.IsNullOrWhiteSpace(account)) throw new BizException("支付宝账号不能为空");
            if (string.IsNullOrWhiteSpace(realName)) throw new BizException("支付宝账号直实姓名不能为空");

            w.AliPayAccount = account;
            w.AliPayAccountName = realName;

            return efUnitOfWork.Commit() > 0;
        }

        public bool SetWxPayInfo(int uid, string phoneCode, string account, string realName)
        {
            var u = userRepository.GetByKey(uid);
            var code = smsCodeRepository.Entities.FirstOrDefault(i => i.Phone == u.Phone && i.SmsCodeType == SmsCodeType.设置支付宝微信 && i.SmsCode == phoneCode);

            if (code == null)
            {
                throw new BizException("手机验证码不正确");
            }
            code.Valid();
            code.IsUse = true;

            var w = walletRepository.Entities.FirstOrDefault(i => i.UserID == uid);

            if (string.IsNullOrWhiteSpace(account)) throw new BizException("微信账号不能为空");
            if (string.IsNullOrWhiteSpace(realName)) throw new BizException("微信账号直实姓名不能为空");

            w.WxPayAccount = account;
            w.WxPayAccountName = realName;

            return efUnitOfWork.Commit() > 0;
        }

        public bool IncomeToCharge(int uid, int money)
        {
            var w = walletRepository.Entities.FirstOrDefault(i => i.UserID == uid);
            if (w.InComeBlance < money) throw new BizException("钱包金额不足,操作失败");

            walletService.ChangeInComeWallet(uid, -money, 0, 0, null,0, FinancialBizType.佣金钱包转发布钱包, "收入钱包转到发布钱包", "收入钱包转到发布钱包");
            walletService.ChangeChargeWallet(uid, money, 0, null, FinancialBizType.佣金钱包转发布钱包, "收入钱包转到发布钱包", "收入钱包转到发布钱包");

            return efUnitOfWork.Commit() > 0;
        }
    }
}
